package com.mmall.service.Impl;

import com.mmall.common.ServerResponse;
import com.mmall.dao.AddressMapper;
import com.mmall.pojo.Address;
import com.mmall.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("AddressService")
@Transactional
public class AddressServiceImpl implements AddressService{

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public ServerResponse insert(Address address,Integer userId) {

        if (address.getDefaultAddress()!=null&& address.getDefaultAddress()==1){    //当前记录是否被要求成默认地址
            Address oldAddress = addressMapper.selectDefaultAdress(userId);
            if(oldAddress != null){
                oldAddress.setDefaultAddress(0);//取消之前的默认地址
                addressMapper.updateByPrimaryKey(oldAddress);
            }
        }


        if(addressMapper.insertSelective(address)>0){
            return ServerResponse.cerateBySuccessMessage("收件地址添加成功");
        }
        return ServerResponse.createByErrorMessage("收件地址添加失败");
    }

    @Override
    public ServerResponse select(Integer id) {
        Address address = addressMapper.selectByPrimaryKey(id);
        if(address !=null){
            return ServerResponse.cerateBySuccess("查询成功",address);
        }
        return ServerResponse.createByErrorMessage("查询失败");
    }

    @Override
    public ServerResponse update(Address address,Integer userId) {

        if (address.getDefaultAddress()!=null&& address.getDefaultAddress()==1){    //当前记录是否被要求成默认地址
            Address oldAddress = addressMapper.selectDefaultAdress(userId);
            if(oldAddress != null){
                oldAddress.setDefaultAddress(0);//取消之前的默认地址
                addressMapper.updateByPrimaryKey(oldAddress);
            }
        }

        if(addressMapper.updateByPrimaryKeySelective(address)>0){
            return ServerResponse.cerateBySuccessMessage("收件地址更新成功");
        }
        return ServerResponse.createByErrorMessage("收件地址更新失败");
    }

    @Override
    public ServerResponse delete(Integer id) {
        if(addressMapper.deleteByPrimaryKey(id)>0){
            return ServerResponse.cerateBySuccessMessage("地址删除成功");
        }
        return ServerResponse.createByErrorMessage("地址删除失败");
    }

    public  ServerResponse findAddressListByUserId(Integer userId){
        List<Address> addressList = addressMapper.selectAddressListByUserId(userId);
        if(addressList!=null && addressList.size()>0){
            return ServerResponse.cerateBySuccess("查询成功",addressList);
        }
        return ServerResponse.createByErrorMessage("无列表信息");
    }
}
